package clientes.Dao;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;

import clientes.cliente.Cliente;
import conexao.Conexao;

public class RepositorioCadastroClienteDAO implements IRepositorioCadastroClienteDAO {

	private Connection conn = null;
	
	public void inserirCliente(Cliente cliente) throws SQLException, ClassNotFoundException {
		this.conn = Conexao.getConexao();
		
		PreparedStatement pstmt = this.conn.prepareStatement
				("INSERT INTO cliente(nome,login,senha,cpf) VALUES (upper(?),upper(?),upper(?), upper(?));");
		pstmt.setString(1, cliente.getNome());
		pstmt.setString(2, cliente.getLogin());
		pstmt.setString(3, cliente.getSenha());
		pstmt.setString(4, cliente.getCpf());
		pstmt.executeUpdate();
	}

	
	public boolean validaLogin(String login, String senha) throws ClassNotFoundException, SQLException{
		this.conn = Conexao.getConexao();
		boolean existe = false;
				
			PreparedStatement psmt = conn.prepareStatement
					("SELECT * FROM cliente WHERE login = upper(?) and senha = upper(?)");
				psmt.setString(1, login);
				psmt.setString(2, senha);
				ResultSet rs = psmt.executeQuery();
		
				if (rs.next()){
					existe = true;
				}			
				return existe;		
		}
				

	@Override
	public boolean isExiste(String nome) throws ClassNotFoundException, SQLException {
		this.conn = Conexao.getConexao();		
		boolean existe = false;
		
	       PreparedStatement psmt = conn.prepareStatement
	    		   ("SELECT nome FROM cliente WHERE nome = upper(?)");  
	            psmt.setString(1, nome);   
	            ResultSet rs = psmt.executeQuery();  

	            if (rs.next()) {  
	                existe = true;  
	            }   
	            return existe;   	
		}

	


	@Override
	public Collection<Cliente> localizarCliente(String nome) throws SQLException, ClassNotFoundException {
this.conn = Conexao.getConexao();
		
		Collection<Cliente> listaClienteNome = new LinkedList<Cliente>();
		
		PreparedStatement ps = conn.prepareStatement("SELECT * FROM cliente WHERE nome = upper(?)");
		ps.setString(1, nome);
				 
		ResultSet rs = ps.executeQuery();
		
		Cliente cliente= null;
		
		while(rs.next()){
			cliente = new Cliente();
			cliente.setNome(rs.getString("nome"));
			cliente.setLogin(rs.getString("login"));
			cliente.setSenha(rs.getString("senha"));	
			
			listaClienteNome.add(cliente);
		}		
		return listaClienteNome;	
	}


	@Override
	public void excluirCliente(String nome) throws ClassNotFoundException, SQLException {
		this.conn= Conexao.getConexao();
		PreparedStatement ps = conn.prepareStatement
				("DELETE FROM cliente WHERE nome = upper(?)");
		ps.setString(1, nome);
		ps.executeQuery();
	}


}
